import {Injectable} from '@angular/core';
import {CookieService} from 'ngx-cookie';
import * as crypto from 'crypto-js';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {ActivatedRoute} from '@angular/router';


@Injectable({
    providedIn: 'root'
})
export class CommonService {
    public apiHost = 'http://langren.com/';
    public aeskey = '#PanApi@AES_Key_';  // 密钥
    public aesiv = '1234567890123456';
    public image_host = 'http://uploader.com';
    public video_host = 'http://uploader.com';

    constructor(private http: HttpClient, private route: ActivatedRoute, private cookieService: CookieService) {
    }


    /**
     * 获取当前频道
     */
    getChannel() {
        const arrUrl = this.getUrlPath().split('/');
        return arrUrl[0];
    }

    /**
     * 获取url参数
     * @return json
     */
    getUrlParams(url = document.location.toString()) {
        const obj = {}; // 声明对象
        if (url.indexOf('?') != -1) {
            url = url.split('?')[1];
            const params = url.split('&');
            for (let i = 0; i < params.length; i++) {
                const param = params[i].split('=');
                obj[param[0]] = param[1]; // 为对象赋值
            }
        }

        return obj;
    }


    /**
     * 获取当前url路径
     */
    getUrlPath() {
        const url = document.location.toString();
        const arrUrl = url.split('//');

        const start = arrUrl[1].indexOf('/') + 1;
        let relUrl = arrUrl[1].substring(start); // stop省略，截取从start开始到结尾的所有字符

        if (relUrl.indexOf('?') != -1) {
            relUrl = relUrl.split('?')[0];
        }
        return relUrl;
    }

    /**
     * 获取用户信息
     */
    getUserInfo() {
        const $user = this.getItem('user');
        if ($user) {
            return JSON.parse($user);
        } else {
            return false;
        }
    }

    /**
     * @description 处理事件
     * @param data http请求返回的数据
     * @param success 成功后的回调函数
     * @param other 其他情况下的回调函数
     * @param options 设置一些设置
     */
    resultHandler(data, success?, encrypt = true) {
        if (data) {
            const msg = data['message'];
            switch (data['status']) {
                case 1:
                    if (success) {
                        let result = '';
                        if (data['data']) {
                            let aesData: any;
                            if (encrypt) {
                                aesData = this.decrypt(data['data']);
                            } else {
                                aesData = data['data'];
                            }
                            if (typeof (aesData) === 'string') {
                                result = JSON.parse(aesData);
                            } else {
                                result = aesData;
                            }
                        }
                        success.apply(this, [msg, result]);
                    }
                    break;
                default:
                    success.apply(this, [msg, '']);
                    break;
            }
        }
    }


    // 加密
    encrypt(data) {
        const key = crypto.enc.Utf8.parse(this.aeskey);
        const iv = crypto.enc.Utf8.parse(this.aesiv);
        const encrypted = crypto.AES.encrypt(data, key,
            {
                iv: iv,
                mode: crypto.mode.CBC,
                padding: crypto.pad.Pkcs7
            });
        return encrypted.toString();    // 返回的是base64格式的密文
    }

    // 解密
    decrypt(encrypted) {
        const key = crypto.enc.Utf8.parse(this.aeskey);
        const iv = crypto.enc.Utf8.parse(this.aesiv);
        const decrypted = crypto.AES.decrypt(encrypted, key,
            {
                iv: iv,
                mode: crypto.mode.CBC,
                padding: crypto.pad.Pkcs7
            });
        return decrypted.toString(crypto.enc.Utf8);      //
    }

    /**
     * get提交
     * @param url
     */
    get(url) {
        return this.http.get(url);
    }

    /**
     * @description 使用post方法请求参数
     * @param url api请求路径
     * @param data post的参数
     */
    post(url, data) {
        data['time'] = this.get_time();
        data = JSON.stringify(data);
        const sign = this.encrypt(data);

        const headers = {
            headers: new HttpHeaders({'Content-Type': 'application/json', 'sign': sign})
        };
        return this.http.post(this.apiHost + url, {'params': sign}, headers);
    }

    get_time() {
        const time = (new Date()).getTime().toString().substr(0, 10);
        return time;
    }

    clear(): void {
        this.cookieService.removeAll();
    }

    getItem(key: string): string {
        return this.cookieService.get(key);
    }

    getList(index: number): string {
        return this.cookieService.getAll().propertyIsEnumerable[index];
    }

    removeItem(key: string): void {
        this.cookieService.remove(key);
    }

    /**
     * @description 当前时间推后多少时间
     * @param time 时间，默认推后2个小时
     */
    getAfterNow(time = 2 * 60 * 60 * 1000): Date {
        const exp = new Date();
        exp.setTime(exp.getTime() + time);
        return exp;
    }

    setItem(key: string, data: string): void {
        this.cookieService.put(key, data, {
            // expires: this.getAfterNow().toUTCString()
        });
    }


    /**
     * 时间戳格式化函数
     * @param  {string} format    格式
     * @param  {int}    timestamp 要格式化的时间 默认为当前时间
     * @return {string}           格式化的时间字符串
     */
    add0(m) {
        return m < 10 ? '0' + m : m;
    }

    getDate(shijianchuo) {
        // shijianchuo是整数，否则要parseInt转换
        var time = new Date(shijianchuo * 1000);
        var y = time.getFullYear();
        var m = time.getMonth() + 1;
        var d = time.getDate();
        var h = time.getHours();
        var mm = time.getMinutes();
        var s = time.getSeconds();
        return y + '-' + this.add0(m) + '-' + this.add0(d) + ' ' + this.add0(h) + ':' + this.add0(mm) /*+ ':' + this.add0(s)*/;
    }
}
